const express = require('express');
const router = express.Router();
const $sql = require('../db/sqlMap');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const auth = require('../middleware/auth');
const conn = require('../db/connectMysql');

const SECRET = "2508tqdhckyxbnwjdhstqdnb"

function sep() {
	console.log("=".repeat(50) + '\n');
}

// 登录接口
router.post('/login', (req, res) => {
	console.log('后端正在处理');
	const user = req.body;
	const sel_name = $sql.user.select + " where username = '" + user.username + "'";
	console.log(sel_name);
	conn.query(sel_name, user.username, (error, results) => {
		if (error) {
			// throw error;
			console.log('数据库错误');
			console.log(error); sep();
			res.status(500).json({
				statusCode: -2,
				message: "用户表查询错误"
			})
		}
		const myUser = results[0];
		console.log(myUser)
		if (myUser === undefined) {
			res.send({
				statusCode: -1,
				message: "用户不存在"
			});  // -1 表示查询不到，用户不存在，即邮箱填写错误
		} else {
			const isPasswordValid = bcrypt.compareSync(
				user.password,
				myUser.password
			);
			if (isPasswordValid) {
				const token = jwt.sign({
					id: String(myUser.user_id),
				}, SECRET)
				res.send({
					statusCode: 0,
					message: "登录成功",
					token: token,
				});// 0 表示用户存在并且邮箱密码正确
			} else {
				console.log('密码错误'); sep();
				res.send({
					statusCode: 1,
					message: "密码错误"
				});  // 1 表示用户存在，但密码不正确
			}
		}
	})
});

// 注册接口
router.post('/register', (req, res) => {
	const params = req.body;
	const sel_sql = $sql.user.select + " where username = '" + params.username + "'";
	const add_sql = $sql.user.add;
	console.log(sel_sql);

	conn.query(sel_sql, params.username, (error, results) => {
		if (error) {
			console.log('数据库错误');
			console.log(error); sep();
			res.status(500).json({
				statusCode: -2,
				message: "用户表查询错误"
			})
		}
		if (results.length != 0 && params.username == results[0].username) {
			res.send({
				statusCode: -1,
				message: "用户已存在"
			});   // -1 表示用户名已经存在
		} else {
			var salt = bcrypt.genSaltSync(10);
			var hash = bcrypt.hashSync(params.password, salt);
			conn.query(add_sql, [params.username, hash, 'normal'], (err, rst) => {
				if (err) {
					console.log('数据库错误');
					console.log(err); sep();
					res.status(500).json({
						statusCode: -2,
						message: "用户表添加错误"
					})
				} else {
					console.log('用户创建成功');
					console.log(rst); sep();
					res.send({
						statusCode: 0,
						message: "用户创建成功"
					}); // 0 表示用户创建成功
				}
			});
		}
	});
});

router.post('/all_users', auth, (req, res) => {
	const sel_all = $sql.user.select;
	try {
		let a = req.user
			.then(ress => {
				var restr = JSON.stringify(ress);
				var redata = JSON.parse(restr)[0];
				conn.query(sel_all, (error, results) => {
					if (error) {
						// throw error;
						console.log("查询用户操作错误。错误信息为：");
						console.log(errrr); sep();
						res.status(500).json({
							statusCode: -1,
							message: "查询用户操作错误"
						})
					} else {
						if (redata == undefined || redata.user_id == undefined) {
							console.log('无效的Token'); sep();
							res.status(401).json({
								statusCode: 0,
								message: "无效的Token，找不到对应用户"
							})
						}
						else if (redata.power == 'normal') {
							console.log('普通用户没有权限。'); sep();
							res.status(403).json({
								statusCode: 0,
								message: "普通用户没有权限"
							});
						} else {
							console.log('显示所有用户'); sep();
							res.json({
								statusCode: 1,
								message: "ok",
								data: results
							});
						}
					}
				})
			})
			.catch(err => {
				// .catch 返回报错信息
				console.error('鉴权出错');
				console.error(err); sep();
				res.status(500).json({
					statusCode: -1,
					message: "服务端鉴权出错。"
				})
			})
	} catch (e) {
		console.error(e); sep();
		res.status(401).json({
			statusCode: 0,
			message: "未登录"
		})
	}
})

router.post('/delete', auth, (req, res) => {
	const uname = req.body.username;
	const desql = $sql.user.del + " where username = ?";
	const sesql = $sql.user.select + " where username = ?";
	try {
		let a = req.user.
			then(ress => {
				var restr = JSON.stringify(ress);
				var redata = JSON.parse(restr)[0];
				conn.query(sesql, uname, (err, resu) => {
					if (err || resu.length == 0) {
						if (err) {
							console.log(err); sep();
							res.status(500).json({
								statusCode: -1,
								message: "数据库操作错误"
							})
						}
						else {
							console.log("结果为空"); sep();
							res.status(404).json({
								statusCode: -1,
								message: "找不到用户"
							})
						}
					} else {
						if (redata == undefined || redata.user_id == undefined) {
							console.log('无效的Token'); sep();
							res.status(401).json({
								statusCode: 0,
								message: "无效的Token，找不到对应用户"
							})
						} else if (redata.power == 'normal') {
							console.log('普通用户没有权限删除。'); sep();
							res.status(403).json({
								statusCode: 0,
								message: "普通用户没有权限"
							});
						} else if (redata.power == 'admin' && (resu[0].power == 'admin' || resu[0].power == 'root')) {
							console.log('普通管理员没有权限删除。'); sep();
							res.status(403).json({
								statusCode: 0,
								message: "普通管理员没有权限"
							})
						} else if (resu[0].power == 'root') {
							console.log("至高无上的gxk不能被删除"); sep();
							res.status(403).json({
								statusCode: 0,
								message: "至高无上的gxk不能被删除"
							})
						} else {
							conn.query(desql, uname, (error, results) => {
								if (error) {
									console.error('删除失败');
									console.error(err); sep();
									res.status(500).json({
										statusCode: -1,
										message: "数据库错误"
									})
								} else {
									conn.query('alter table user auto_increment = 1', (er, re) => {
										if (er) {
											console.error('更新失败')
											console.error(er); sep();
											res.status(500).json({
												statusCode: -1,
												message: "数据库错误"
											})
										} else {
											console.log("更新成功"); sep();
											res.json({
												statusCode: 1,
												message: "删除成功"
											});
										}
									})
								}
							})
						}
					}
				})
			})
			.catch(err => {
				// .catch 返回报错信息
				console.error('鉴权出错');
				console.error(err); sep();
				res.status(500).json({
					statusCode: -1,
					message: "服务端鉴权出错。"
				})
			})
	} catch (e) {
		console.error(e); sep();
		res.status(401).json({
			statusCode: 0,
			message: "未登录"
		})
	}
})

router.post('/distribute_power', auth, (req, res) => {
	const uname = req.body.username;
	const pwr = req.body.power;
	const upsql = $sql.user.update + " power = ? where username = ?";
	const sesql = $sql.user.select + " where username = ?";
	try {
		let a = req.user.
			then(ress => {
				var restr = JSON.stringify(ress);
				var redata = JSON.parse(restr)[0];
				conn.query(sesql, uname, (err, resu) => {
					if (err || resu.length == 0) {
						if (err) {
							console.error(err); sep();
							res.status(500).json({
								statusCode: -1,
								message: "数据库操作错误"
							})
						}
						else {
							console.log("找不到用户"); sep();
							res.status(404).json({
								statusCode: -1,
								message: "找不到用户"
							})
						}
					} else {
						if (redata == undefined || redata.user_id == undefined) {
							console.log('无效的Token'); sep();
							res.status(401).json({
								statusCode: 0,
								message: "无效的Token，找不到对应用户"
							})
						} else if (redata.power != 'root') {
							console.log('普通用户和普通管理员没有权限修改。'); sep();
							res.status(401).json({
								statusCode: 0,
								message: "普通用户和普通管理员没有权限"
							});
						} else if (resu[0].power == 'root') {
							console.log("至高无上的gxk不能被修改"); sep();
							res.status(401).json({
								statusCode: 0,
								message: "至高无上的gxk不能被修改"
							})
						} else {
							conn.query(upsql, [pwr, uname], (error, results) => {
								if (error) {
									console.error('修改失败');
									console.log(err); sep();
									res.status(500).json({
										statusCode: -1,
										message: "修改失败"
									})
								} else {
									console.log("修改成功"); sep();
									res.json({
										statusCode: 1,
										message: "修改成功"
									});
								}
							})
						}
					}
				})
			})
			.catch(err => {
				// .catch 返回报错信息
				console.error('鉴权出错');
				console.error(err); sep();
				res.status(500).json({
					statusCode: -1,
					message: "服务端鉴权出错。"
				})
			})
	} catch (e) {
		console.error(e); sep();
		res.status(401).json({
			statusCode: 0,
			message: "未登录"
		})
	}
})

//测试
router.post('/test', auth, (req, res) => {
	try {
		let a = req.user.
			then(ress => {
				res.send(ress);
				console.log(ress);
			})
			.catch(err => {
				// .catch 返回报错信息
				console.log(err)
			})
	}
	catch (e) {
		console.error(e); sep();
	}
})

module.exports = router;